package com.cxm.weilai.util;

import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.commons.beanutils.BeanUtilsBean;
import org.apache.commons.beanutils.DynaBean;
import org.apache.commons.beanutils.DynaProperty;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * 公用方法.
 *
 * @author 1456006653@qq.com
 */
public class BeanUtil {
    private static Log log = LogFactory.getLog(BeanUtil.class);

    /**
     * 判断是否为空.
     *
     * @param object 传入参数
     * @return boolean
     */
    public static boolean isEmpty(Object object) {
        if (object == null) return true;
        if ((object instanceof String)) {
            if (((String) object).trim().length() == 0) {
                return true;
            }
        } else if ((object instanceof Collection)) {
            if (((Collection<?>) object).isEmpty()) {
                return true;
            }
        } else if (object.getClass().isArray()) {
            if (((Object[]) object).length == 0) {
                return true;
            }
        } else if ((object instanceof Map)) {
            if (((Map<?, ?>) object).isEmpty()) {
                return true;
            }
        } else if ((object instanceof Long)) {
            if ((Long) object == 0) {
                return true;
            }
        } else if ((object instanceof Short)) {
            if ((Short) object == 0) {
                return true;
            }
        } else {
            return false;
        }
        return false;
    }

    public static boolean isNotEmpty(Object object) {
        return !isEmpty(object);
    }

    public static boolean isNotEmpty(Long ong) {
        return !isEmpty(ong);
    }

    /**
     * 获取类型名称.
     *
     * @param clazzClass   类
     * @param propertyType 属性类型
     * @return String[]
     */
    @SuppressWarnings("unchecked")
    public static String[] getTypeName(@SuppressWarnings("rawtypes") Class clazzClass, String propertyType) {
        @SuppressWarnings("rawtypes")
        List list = new ArrayList();
        try {
            BeanInfo beanInfo = Introspector.getBeanInfo(clazzClass);
            PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();

            for (PropertyDescriptor property : propertyDescriptors) {
                String type = property.getPropertyType().getSimpleName();
                if (type.equals(propertyType)) {
                    list.add(property.getName());
                }
            }
            return (String[]) list.toArray(new String[list.size()]);
        } catch (Exception exception) {
            return new String[]{};
        }
    }

    /**
     * Map --> Bean 1: 利用Introspector,PropertyDescriptor实现 Map --> Bean.
     *
     * @param map Map
     * @param obj Object
     * @return Object
     */
    public static Object transMap2Bean(Map<String, Object> map, Object obj) {

        try {
            BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass());
            PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();

            for (PropertyDescriptor property : propertyDescriptors) {
                String key = property.getName();

                if (map.containsKey(key)) {
                    Object value = map.get(key);
                    Method setter = property.getWriteMethod();
                    // 得到property对应的setter方法
                    String type = property.getPropertyType().getSimpleName();
                    if (type.equals("Date")) {
                        Date date = DateUtil.parseSIMDateTime2Date(value.toString());
                        if (date != null) {
                            setter.invoke(obj, date);
                            continue;
                        }
                    }
                    setter.invoke(obj, value);
                }
            }
        } catch (Exception exception) {
            log.error("transMap2Bean Error " + exception);
        }

        return obj;

    }

    /**
     * Bean --> Map 1: 利用Introspector和PropertyDescriptor 将Bean --> Map.
     *
     * @param obj Object
     * @return Map
     */
    public static Map<String, Object> transBean2Map(Object obj) {

        if (obj == null) {
            return null;
        }
        Map<String, Object> map = new HashMap<String, Object>();
        try {
            BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass());
            PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
            for (PropertyDescriptor property : propertyDescriptors) {
                String key = property.getName();
                if (!key.equals("class")) {
                    Method getter = property.getReadMethod();
                    Object value = getter.invoke(obj);
                    map.put(key, value);
                    if (key.equals("date")) {
                        map.put(key, DateUtil.getSIMDateTime2String((Date) value));
                    }
                }

            }
        } catch (Exception exception) {
            log.error("transBean2Map Error " + exception);
        }

        return map;

    }

    /**
     * copyNotNullProperties.
     *
     * @param dest Object
     * @param orig Object
     * @throws IllegalAccessException    illegalAccessException
     * @throws InvocationTargetException invocationTargetException
     */
    public static void copyNotNullProperties(Object dest, Object orig) throws IllegalAccessException,
            InvocationTargetException {
        BeanUtilsBean beanUtils = BeanUtilsBean.getInstance();

        if (dest == null) {
            throw new IllegalArgumentException("No destination bean specified");
        }
        if (orig == null) {
            throw new IllegalArgumentException("No origin bean specified");
        }
        if (log.isDebugEnabled()) {
            log.debug("BeanUtils.copyProperties(" + dest + ", " + orig + ")");
        }

        if (orig instanceof DynaBean) {
            DynaProperty[] origDescriptors = ((DynaBean) orig).getDynaClass().getDynaProperties();
            for (int i = 0; i < origDescriptors.length; ++i) {
                String name = origDescriptors[i].getName();
                if ((!beanUtils.getPropertyUtils().isReadable(orig, name))
                        || (!beanUtils.getPropertyUtils().isWriteable(dest, name))) continue;
                Object value = ((DynaBean) orig).get(name);
                beanUtils.copyProperty(dest, name, value);
            }
        } else if (orig instanceof Map) {

            @SuppressWarnings("rawtypes")
            Iterator entries = ((Map) orig).entrySet().iterator();
            while (entries.hasNext()) {
                @SuppressWarnings("rawtypes")
                Map.Entry entry = (Map.Entry) entries.next();
                String name = (String) entry.getKey();
                if (beanUtils.getPropertyUtils().isWriteable(dest, name))
                    beanUtils.copyProperty(dest, name, entry.getValue());
            }
        } else {
            PropertyDescriptor[] origDescriptors = beanUtils.getPropertyUtils().getPropertyDescriptors(orig);
            for (int i = 0; i < origDescriptors.length; ++i) {
                String name = origDescriptors[i].getName();
                if ("class".equals(name)) {
                    continue;
                }
                if ((!beanUtils.getPropertyUtils().isReadable(orig, name))
                        || (!beanUtils.getPropertyUtils().isWriteable(dest, name))) continue;
                try {
                    Object value = beanUtils.getPropertyUtils().getSimpleProperty(orig, name);
                    if (value != null) beanUtils.copyProperty(dest, name, value);
                } catch (NoSuchMethodException localNoSuchMethodException) {
                }
            }
        }
    }
}
